const pty = require('node-pty');
const os = require('os');
const WebSocket = require('ws');
const shell = os.platform() === 'win32' ? 'powershell.exe' : 'bash';

const wss = new WebSocket.Server({ port: 38888 });
const termMap = new Map(); //存储 pty 实例，通过 pid 映射
wss.on('connection', (ws) => {
    // console.log('socket connection success');
    const ptyProcess = pty.spawn(shell, [], {
        name: 'xterm-color',
        cols: 80,
        rows: 30,
        cwd: process.env.HOME,
        env: process.env
    });

    setTimeout(() => {
        let newData = JSON.stringify({
            data: JSON.stringify({ sshStatus: 'INIT', msg: '初始化中……' }),
            type: 'Status'
        })
        ws.send(newData)
    }, 1000)
    setTimeout(() => {
            let newData = JSON.stringify({
                data: JSON.stringify({ sshStatus: 'CONNECTED', msg: '连接成功' }),
                type: 'Status'
            })
            ws.send(newData)
                // process.stdout.write(newData);
        }, 3000)
        //接受数据
    ws.on('message', (res) => {
        // console.log(res, res)
        const data = JSON.parse(res)
        const type = data.type
        if (type === 'Conn') {
            const dataId = JSON.parse(data.data).dataId
                // ptyProcess.write(dataId)
        } else if (type === 'CtlMsg') {
            const msg = JSON.parse(data.data)
            ptyProcess.write(msg.ctlMsg)
        }
        // ptyProcess.write(res)
    });
    //发送数据
    ptyProcess.on('data', function(data) {


        let newData = JSON.stringify({
            data: JSON.stringify({ msg: data }),
            type: 'TerminalMsg'
        })
        ws.send(newData)
            // process.stdout.write(newData);

    });
});

// function nodeEnvBind() {
//     //绑定当前系统 node 环境
//     const term = pty.spawn(shell, ["--login"], {
//         name: "xterm-color",
//         cols: 80,
//         rows: 30,
//         cwd: process.env.HOME,
//         env: process.env,
//     });
//     termMap.set(term.pid, term);
//     return term;
// }   let newData = ''
// let newData = JSON.stringify({
//     data: JSON.stringify({ sshStatus: 'INIT', msg: obj.dataId }),
//     type: 'Status'
// })
// setTimeout(() => {
//     ws.send(newData)
//     process.stdout.write(newData);
// }, 10)